package com.ant.myagile

import javax.servlet.ServletContext

import microsoft.exchange.webservices.data.EmailMessage
import microsoft.exchange.webservices.data.ExchangeCredentials
import microsoft.exchange.webservices.data.ExchangeService
import microsoft.exchange.webservices.data.ExchangeVersion
import microsoft.exchange.webservices.data.MessageBody
import microsoft.exchange.webservices.data.WebCredentials


class MailService {

	final String username = "my-agile";
	final String password = "r8mbtmv2!I";
	final String exchangeServices="https://192.168.70.220/EWS/Exchange.asmx"

	ExchangeService initService(){
		try {
			ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
			ExchangeCredentials credentials = new WebCredentials(username,password);
			service.setCredentials(credentials);
			service.setUrl(new URI(exchangeServices));
			return service;
		}
		catch(Exception e) {
			println 'Init Mail Services fails!'
			e.printStackTrace()
		}
	}

	public static boolean isValidEmail(String emailAddress) {
		return emailAddress.matches("[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}");
	}

	def realPath(ServletContext servletContext){
		String hostName = InetAddress.getLocalHost().getHostName()
		String path= servletContext.getContextPath()
		String port = "";
		if (grails.util.GrailsUtil.developmentEnv) port = ":8080"
		return "http://${hostName}${port}${path}/"
	}

	def sendMail(String subject,String content,String toEmail) throws Exception{
				ExchangeService service = initService();
		        EmailMessage msg= new EmailMessage(service);
		        msg.setSubject(subject);
		        MessageBody body = new MessageBody(content);
				 msg.setBody(body);
		        msg.getToRecipients().add(toEmail);
		        msg.sendAndSaveCopy();
	}

	def createAutoNumber(){
		String uuid = UUID.randomUUID().toString();
		uuid = uuid.replace("-", "")
		return uuid
	}
}
